
#include "etcd.hpp"
#include "channel.hpp"
#include "utils.hpp"
#include <gflags/gflags.h>
#include <gtest/gtest.h>
#include <thread>
#include "user.pb.h"
#include "base.pb.h"

DEFINE_bool(run_mode,false,"程序运行的模式,false-调试,true-发布");
DEFINE_string(log_file,"","发布模式下,用于指定日志输出的文件");
DEFINE_int32(log_level,0,"发布模式下,用于指定日志输出等级");

DEFINE_string(etcd_host,"http://127.0.0.1:2379","服务注册中心地址");
DEFINE_string(base_service,"/service","服务监控根目录");
DEFINE_string(user_service,"/service/user_service","服务监控根目录");

ServiceManager::ptr _user_channels;


void reg_user(const std::string& nickname,const std::string& pswd)
{
    auto channel = _user_channels->choose(FLAGS_user_service);//获取通信信道
    ASSERT_TRUE(channel);

    wzl::UserRegisterReq req;
    req.set_request_id(wzl::uuid());
    req.set_nickname(nickname);
    req.set_password(pswd);

    wzl::UserRegisterRsp rsp;
    brpc::Controller cntl;
    wzl::UserService_Stub stub(channel.get());
    stub.UserRegister(&cntl, &req, &rsp, nullptr);
    ASSERT_FALSE(cntl.Failed());
    ASSERT_TRUE(rsp.success());
}
    
void set_user_avatar(const std::string &uid, const std::string &avatar) 
{
    auto channel = _user_channels->choose(FLAGS_user_service);//获取通信信道
    ASSERT_TRUE(channel);
    wzl::SetUserAvatarReq req;
    req.set_request_id(wzl::uuid());
    req.set_user_id(uid);
    req.set_session_id("测试登录会话D");
    req.set_avatar(avatar);
    wzl::SetUserAvatarRsp rsp;
    brpc::Controller cntl;
    wzl::UserService_Stub stub(channel.get());
    stub.SetUserAvatar(&cntl, &req, &rsp, nullptr);
    ASSERT_FALSE(cntl.Failed());
    ASSERT_TRUE(rsp.success());
}

int main(int argc,char* argv[])
{
    testing::InitGoogleTest(&argc,argv);
    google::ParseCommandLineFlags(&argc,&argv,true);
    wzl::init_logger(FLAGS_run_mode,FLAGS_log_file,FLAGS_log_level);

    //1. 先构造Rpc信道管理对象
    _user_channels = std::make_shared<ServiceManager>();
    _user_channels->declared(FLAGS_user_service);
    auto put_cb = std::bind(&ServiceManager::onServiceOnline, _user_channels.get(), std::placeholders::_1, std::placeholders::_2);
    auto del_cb = std::bind(&ServiceManager::onServiceOffline, _user_channels.get(), std::placeholders::_1, std::placeholders::_2);
    // //2. 构造服务发现对象
    Discovery::ptr dclient = std::make_shared<Discovery>(FLAGS_etcd_host, FLAGS_base_service, put_cb, del_cb);
    reg_user("猪妈妈","123456");
    reg_user("猪爸爸","123456");
    reg_user("小猪佩奇","123456");
    reg_user("小猪乔治","123456");
    std::string uid1,uid2,uid3,uid4;
    std::cout<<"输入猪妈妈用户ID";
    std::cin>>uid1;
    std::fflush(stdout);
    std::cout<<"输入猪爸爸用户ID";
    std::cin>>uid2;
    std::fflush(stdout);
    std::cout<<"输入佩奇用户ID";
    std::cin>>uid3;
    std::fflush(stdout);
    std::cout<<"输入乔治用户ID";
    std::cin>>uid4;
    std::fflush(stdout);
    set_user_avatar(uid3,"佩奇头像数据");
    set_user_avatar(uid4,"乔治头像数据");
    set_user_avatar(uid2,"猪爸爸头像数据");
    set_user_avatar(uid1,"猪妈妈头像数据");
    return 0;
}